<template>
  <!-- 获取经纬度 -->
  <el-dialog title="获取经纬度" :visible.sync="amapOpen" width="750px" append-to-body>
    <div class="diy-mx-10">
      <el-form ref="form" :model="smapForm" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item id="tipinput" label="关键字搜索" >
              <!-- <el-input v-model="smapForm.search" /> -->
              <el-select
                v-model="smapForm.search"
                filterable
                remote
                reserve-keyword
                placeholder="请输入地名"
                :no-data-text="'查询失败，请输入正确地名'"
                :popper-class="'g-poi-search-popper'"
                :remote-method="fnRemoteMethod"
                :loading="bPoiSearchLoading"
                @change="fnPoiSearchChange">
                <el-option
                  v-for="item in aPoiSearchOptions"
                  :key="item.value"
                  :label="item.label"
                  :title="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="经纬度" >
              <el-input v-model="smapForm.lnglat" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div id="container"></div>
    </div>
    <div slot="footer" class="dialog-footer diy-mx-10">
      <el-button type="primary" @click="amapSubmit">保 存</el-button>
      <el-button @click="amapOpen = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {
  serviceHost: `${location.origin}/_AMapService`,
  securityJsCode:'5e76796c694743c3b668207b0ae57fe9',
}
export default {
  name: 'Pagination',
  props: {
    formType: {//需要赋值的字段
      type: [Object],
      default:()=>{
        return {
          'longitude':'longitude',
          'latitude':'latitude',
          'details':'details',
        }
      }
    },
    isDetail:{//是否需要详情
      type: [Boolean],
      default:()=>{
        return false
      }
    }
  },
  data() {
    return {
      //地突弹窗
      amapOpen:false,
      oAddMapPlaceSearch: null, // 地图查询服务
      aPoiSearchOptions: [], // 可选择地图列表
      bPoiSearchLoading: false, // 地图搜索 loading
      //地图form
      smapForm:{},
      form:{},
    };
  },

  methods: {
    //地图打开
    mapLoad(form){
      this.initMap()
      this.form = form
      let smapForm = {...this.smapForm}
      smapForm.search = ''
      smapForm.lnglat = this.form[this.formType.longitude] ? this.form[this.formType.longitude] + ',' + this.form[this.formType.latitude] : ''
      this.smapForm = {...smapForm}
      this.amapOpen = true
    },
    //初始化地图
    initMap(){//初始化地图
      AMapLoader.load({
          key:"d37e7aae32c378584d0315d53109c36c",             // 申请好的Web端开发者Key，首次调用 load 时必填
          version:"2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins:['AMap.Geocoder'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap)=>{
        console.log('AMap',AMap)
          this.map = new AMap.Map('container',{
              zoom:13,
              resizeEnable: true, //是否监控地图容器尺寸变化
              center:[116.406315, 39.908775]
          });
          if(this.form[this.formType.longitude]) this.bjMarker(AMap,this.form[this.formType.longitude] || 0,this.form[this.formType.latitude] || 0)
          this.map.on('click', (ev)=> {
            this.map.clearMap();
            // 触发事件的对象var target = ev.target;
            // 触发事件的地理坐标，AMap.LngLat 类型
            var lnglat = ev.lnglat;
            // 触发事件的像素坐标，AMap.Pixel 类型var pixel = ev.pixel;
            // 触发事件类型var type = ev.type;
            this.bjMarker(AMap,lnglat.lng,lnglat.lat)
          });
          this.PlaceSearch(AMap)
      }).catch(e=>{console.log(e);})
    },
    //添加标记点并剧中
    bjMarker(AMap,lng,lat){
        console.log([lng, lat])
        if (this.marker) {
            this.marker.setMap(null);
            this.marker = null;
        }
      this.marker = new AMap.Marker({
        icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: [lng, lat],   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        offset: new AMap.Pixel(-13, -30)
      })
      this.marker.setMap(this.map)
      this.map.setZoomAndCenter(13, [lng, lat])
      let smapForm = {...this.smapForm}
      smapForm.lnglat = lng + ',' + lat
      smapForm.longitude = lng
      smapForm.latitude = lat
      this.smapForm = {...smapForm}
    },
    PlaceSearch(AMap){
      AMap.plugin(['AMap.PlaceSearch', 'AMap.ToolBar'], ()=> {
        this.map.addControl(new AMap.ToolBar());
        this.oAddMapPlaceSearch = new AMap.PlaceSearch({
            type: "", // 数据类别
            pageSize: 10, // 每页结果数,默认10
            pageIndex: 1, // 请求页码，默认1
            extensions: "base" //返回信息详略，默认为base（基本信息）
        }); //构造PlaceSearch类
        AMap.Event.addListener(this.oAddMapPlaceSearch, "complete", (data)=> {
          console.log('complete',data)
            // 监听地图搜索查询完成
            if(data.info === 'OK' && data.poiList && data.poiList.pois && data.poiList.pois.length) {
                this.aPoiSearchOptions = data.poiList.pois.map(v=> ({
                    value: v.id,
                    label: v.name,
                    location: v.location
                }))
            } else {
                this.aPoiSearchOptions = [];
            }
            this.bPoiSearchLoading = false;
        });
        AMap.Event.addListener(this.oAddMapPlaceSearch, "error", (data)=> {
          console.log('error',data)
          // 监听地图搜索查询失败
          this.aPoiSearchOptions = [];
          this.bPoiSearchLoading = false;
        });
      });
    },

    /*
    * @desc 地图远程搜索方法
    * @param query {String} 查询字符
    * */
    fnRemoteMethod(query) {
      if (query !== '' && this.oAddMapPlaceSearch) {
        this.bPoiSearchLoading = true;
        // 根据关键字获取对应城市里相关的POI信息
        this.oAddMapPlaceSearch.search(query);
      } else {
        this.aPoiSearchOptions = [];
      }
    },
    /*
    * @desc 地图搜索关键词发生变化，并添加标记
    * param val {String} 当前选中值
    * */
    fnPoiSearchChange(val) {
      let oFindMap = this.aPoiSearchOptions.find(v=> v.value === val);
      console.log(oFindMap)
      if(oFindMap) {
        // 定位到指定Poi
        let location = oFindMap.location || {}
        this.bjMarker(AMap,location.lng,location.lat)
      }
    },
    //地图选择保存
    amapSubmit(){
      this.form[this.formType.longitude] = this.smapForm.longitude
      this.form[this.formType.latitude] = this.smapForm.latitude
      this.amapOpen = false
      if(!this.isDetail) this.$emit('mapSubmit',this.form)
      if(this.isDetail) this.GeocoderAddress([this.smapForm.longitude,this.smapForm.latitude])
    },
    GeocoderAddress(lnglat){//经纬度获取详细地址
      var geocoder = new AMap.Geocoder({
          // city: "010", //城市设为北京，默认：“全国”
          radius: 1000000 //范围，默认：500
      });
      geocoder.getAddress(lnglat, (status, result)=> {
        if (status === 'complete'&&result.regeocode) {
          console.log('result',result)
            var address = result.regeocode.formattedAddress;
            let form = {...this.form}
            form[this.formType.details] = address
            this.form = {...form}
            this.$emit('mapSubmit',this.form)
            console.log('this.form',this.form)
        }else{
          this.$modal.msgError("根据经纬度查询地址失败");
        }
      });
    },
  }
}
</script>

<style scoped>
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
   -webkit-appearance: none !important;
 }
::v-deep input[type=‘number’] {
   -moz-appearance: textfield !important;
 }
</style>

<style lang="scss">
.amap-icon img,.amap-icon,
.amap-marker-content img{
width: 25px!important;
height: 34px!important;
}
#container {width:650px; height: 300px; }
</style>
